package com.bobo.MD5;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
/**
 * Java 实现消息摘要（MAC）
 * @author win7
 *
 */
public class MACtest {

	private static String bobo="www.baobao.com";
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		JdkMacMD5();
	}

	public static void JdkMacMD5(){
		
		try {
			//1.初始化key秘钥
			KeyGenerator keyGenerator=KeyGenerator.getInstance("HmacMD5");  
			SecretKey secretKey= keyGenerator.generateKey();
			byte[] key= secretKey.getEncoded();
			
			SecretKey restoreSecretKey=new SecretKeySpec(key, "HmacMD5");//还原key
			//2.进行消息摘要
			Mac mac=Mac.getInstance(restoreSecretKey.getAlgorithm());//实例化一个 Mac对象
			mac.init(restoreSecretKey);//初始化mac
			byte[] result= mac.doFinal(bobo.getBytes());//对信息进行消息摘要
			System.out.println("HmacMD5 消息摘要："+Base64.encodeBase64String(result));
		} catch (NoSuchAlgorithmException | InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
